<?php
namespace App\Exports;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * 加载 Excel 模板文件,填入数据后导出
 */
class LoadExcelExport
{
    /**
     * Excel 工作簿对象
     */
    protected $spreadsheet;

    /**
     * Excel 工作表对象
     */
    protected $worksheet;

    public function __construct($file_path)
    {
        if($file_path){
            $this->loadExcel($file_path);
        }
    }

    public static function load($file_path)
    {
        return (new self($file_path));
    }

    /**
     * 加载 Excel 文件
     * @param $file_path
     * @return $this
     */
    public function loadExcel($file_path)
    {
        $this->spreadsheet = IOFactory::load($file_path);
        $this->worksheet = $this->spreadsheet->getActiveSheet();
        return $this;
    }

    /**
     * 切换工作簿
     */
    public function setWorksheet($worksheet){
        $this->worksheet = $this->spreadsheet->getSheetByName($worksheet);
        return $this;
    }


    /**
     * 设置 Excel 工作表数据
     * @param $items
     * @param string $startCell
     * @return $this
     */
    public function setItems($items,$startCell='A1'){
        $this->worksheet->fromArray($items, null, $startCell);
        return $this;
    }

    /**
     * 导出 Excel 文件
     * @param $fileName
     * @return StreamedResponse
     */
    public function download($fileName){
        $writer = new Xlsx($this->spreadsheet);
        
        if(PHP_SAPI === 'cli'){
            $tmpdir = storage_path('app/tmp/' . date('Y-m/d/'));
            if (!is_dir($tmpdir)) {
                mkdir($tmpdir, 0777, true);
            }
            $tempFilePath = $tmpdir. uniqid(). '.xlsx';
            $writer->save($tempFilePath);

            // 使用 Laravel 的 response()->download() 方法:cite[8]
            return response()->download($tempFilePath, $fileName)->deleteFileAfterSend(true);
        }
        // 使用 StreamedResponse 来避免生成临时文件
        return new StreamedResponse(
            function () use ($writer) {
                $writer->save('php://output');
            },
            200,
            [
                'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
                'Cache-Control' => 'max-age=0',
            ]
        );
    }


}